/*
 * EkranLogowania.java
 *
 * Created on 2011-04-03, 11:10:20
 */
package medimg.widok.konto;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.swing.JOptionPane;
import org.hibernate.Session;

/**
 *
 * @author l0nger
 */
public class EkranLogowania extends javax.swing.JDialog {
    private int uprawnieniaZalogowanego;
    /** Creates new form EkranLogowania */
    public EkranLogowania(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(parent);
        // sprawdzenie czy na dysku jest plik z zapisanym haslem i loginem
        // jesli tak - zaladowac te dane do textfieldow
        File file = new File("pass.dat");
        if(file.exists()){
            try{
                RandomAccessFile raf = null;
                raf = new RandomAccessFile(file,"rw");
                getjTextFieldPesel().setText(raf.readLine());
                getjPasswordFieldHaslo().setText(raf.readLine());
                getjCheckBoxZapamietanieHasla().setSelected(true);
                raf.close();
            }
            catch(IOException ex){

            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButtonAnuluj = new javax.swing.JButton();
        jLabelPesel = new javax.swing.JLabel();
        jLabelHaslo = new javax.swing.JLabel();
        jTextFieldPesel = new javax.swing.JTextField();
        jPasswordFieldHaslo = new javax.swing.JPasswordField();
        jCheckBoxZapamietanieHasla = new javax.swing.JCheckBox();
        jButtonZaloguj = new javax.swing.JButton();

        jButton1.setText("Zaloguj");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Logowanie");
        setModal(true);
        setName("Logowanie"); // NOI18N
        setResizable(false);

        jButtonAnuluj.setText("Anuluj");
        jButtonAnuluj.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAnulujActionPerformed(evt);
            }
        });

        jLabelPesel.setText("PESEL");

        jLabelHaslo.setText("Hasło");

        jCheckBoxZapamietanieHasla.setText("Zapamiętaj hasło");

        jButtonZaloguj.setText("Zaloguj");
        jButtonZaloguj.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonZalogujActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelPesel)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldPesel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelHaslo)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jCheckBoxZapamietanieHasla)
                            .addComponent(jPasswordFieldHaslo, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(85, Short.MAX_VALUE)
                .addComponent(jButtonZaloguj)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonAnuluj)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelPesel)
                    .addComponent(jTextFieldPesel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelHaslo)
                    .addComponent(jPasswordFieldHaslo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addComponent(jCheckBoxZapamietanieHasla)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAnuluj)
                    .addComponent(jButtonZaloguj))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonZalogujActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonZalogujActionPerformed
        if(walidacjaDanych())
        {
            uprawnieniaZalogowanego = medimg.hibernate.HibernateUtil.connectToDataBase(getjTextFieldPesel().getText(),
                    java.lang.String.valueOf(getjPasswordFieldHaslo().getPassword()));
            if(medimg.hibernate.HibernateUtil.getSessionFactory().isClosed()){
                JOptionPane.showConfirmDialog(this,"Podano zle dane uzytkownika.","Nie polaczono",JOptionPane.DEFAULT_OPTION);
                medimg.hibernate.HibernateUtil.disconnectFromDataBase();
            }
            else{
                int result = JOptionPane.showConfirmDialog(this,"Polaczono...","Polaczono",JOptionPane.DEFAULT_OPTION);
                if(getjCheckBoxZapamietanieHasla().isSelected()){
                    try{
                        FileWriter file = new FileWriter("pass.dat");
                        BufferedWriter out = new BufferedWriter(file);
                        out.write(getjTextFieldPesel().getText()+"\n");
                        out.write(java.lang.String.valueOf(getjPasswordFieldHaslo().getPassword())+"\n");
                        out.close();
                    }
                    catch(IOException ex){

                    }
                }
                else{
                    try{
                        File file = new File("pass.dat");
                        file.delete();
                    }
                    catch(IllegalArgumentException ex){

                    }
                }
                if(result==0){
                    this.dispose();
                }
            }
        }
        else
        {
            JOptionPane.showConfirmDialog(this,"Bledne dane! Wprowadz poprawnie wartosci.","Blad",JOptionPane.DEFAULT_OPTION);
        }
    }//GEN-LAST:event_jButtonZalogujActionPerformed

    private void jButtonAnulujActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAnulujActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButtonAnulujActionPerformed

    // TODO metoda ktora zwraca pesel zalogowanego typa oraz jego poziom uprawnien (sluzy do
    // aktywacji odpowiednich menu)

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                EkranLogowania dialog = new EkranLogowania(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonAnuluj;
    private javax.swing.JButton jButtonZaloguj;
    private javax.swing.JCheckBox jCheckBoxZapamietanieHasla;
    private javax.swing.JLabel jLabelHaslo;
    private javax.swing.JLabel jLabelPesel;
    private javax.swing.JPasswordField jPasswordFieldHaslo;
    private javax.swing.JTextField jTextFieldPesel;
    // End of variables declaration//GEN-END:variables

    private boolean walidacjaDanych(){
        if(getjPasswordFieldHaslo().getPassword().length != 0 &&
                czyPrawidlowyPesel(jTextFieldPesel.getText()))
            return true;
        else
            return false;
    }


    private boolean czyPrawidlowyPesel(java.lang.String str){
        if(str.length() != 11)
            return false;
        for(int i=0; i<str.length();i++){
            if(!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }
    /**
     * @return the jTextFieldPesel
     */
    public javax.swing.JTextField getjTextFieldPesel() {
        return jTextFieldPesel;
    }

    /**
     * @param jTextFieldPesel the jTextFieldPesel to set
     */
    public void setjTextFieldPesel(javax.swing.JTextField jTextFieldPesel) {
        this.jTextFieldPesel = jTextFieldPesel;
    }

    /**
     * @return the jCheckBoxZapamietanieHasla
     */
    public javax.swing.JCheckBox getjCheckBoxZapamietanieHasla() {
        return jCheckBoxZapamietanieHasla;
    }

    /**
     * @param jCheckBoxZapamietanieHasla the jCheckBoxZapamietanieHasla to set
     */
    public void setjCheckBoxZapamietanieHasla(javax.swing.JCheckBox jCheckBoxZapamietanieHasla) {
        this.jCheckBoxZapamietanieHasla = jCheckBoxZapamietanieHasla;
    }

    /**
     * @return the jPasswordFieldHaslo
     */
    public javax.swing.JPasswordField getjPasswordFieldHaslo() {
        return jPasswordFieldHaslo;
    }

    /**
     * @param jPasswordFieldHaslo the jPasswordFieldHaslo to set
     */
    public void setjPasswordFieldHaslo(javax.swing.JPasswordField jPasswordFieldHaslo) {
        this.jPasswordFieldHaslo = jPasswordFieldHaslo;
    }

    /**
     * @return the uprawnieniaZalogowanego
     */
    public int getUprawnieniaZalogowanego() {
        return uprawnieniaZalogowanego;
    }

    /**
     * @param uprawnieniaZalogowanego the uprawnieniaZalogowanego to set
     */
    public void setUprawnieniaZalogowanego(int uprawnieniaZalogowanego) {
        this.uprawnieniaZalogowanego = uprawnieniaZalogowanego;
    }


}
